package com.ply.flashsalessystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ply.flashsalessystem.annotation.AuthorityName;
import com.ply.flashsalessystem.annotation.StoreAuthority;
import com.ply.flashsalessystem.entity.pojo.Store;
import com.ply.flashsalessystem.entity.pojo.User;
import com.ply.flashsalessystem.entity.result.Result;
import com.ply.flashsalessystem.entity.status.OrderStatus;
import com.ply.flashsalessystem.entity.status.StoreAmountStatus;
import com.ply.flashsalessystem.entity.status.UserAmountStatus;
import com.ply.flashsalessystem.entity.vo.UserAmountVo;
import com.ply.flashsalessystem.entity.vo.store.OrderForStoreVo;
import com.ply.flashsalessystem.entity.vo.store.StoreVo;
import com.ply.flashsalessystem.entity.vo.store.UserToStoreVo;
import com.ply.flashsalessystem.entity.wrapper.StoreAmountWrapper;
import com.ply.flashsalessystem.entity.wrapper.StoreWrapper;
import com.ply.flashsalessystem.entity.wrapper.UserWrapper;
import com.ply.flashsalessystem.entity.wrapper.WrapperOrder;
import com.ply.flashsalessystem.service.OrderForGoodsService;
import com.ply.flashsalessystem.service.StoreAmountService;
import com.ply.flashsalessystem.service.StoreService;
import com.ply.flashsalessystem.service.UserService;
import com.ply.flashsalessystem.utils.RuleUtils;
import com.ply.flashsalessystem.utils.UserUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author XiaoPan
 * @since 2022-03-23
 */
@RestController
@RequestMapping("/store")
@Slf4j
@CrossOrigin
public class StoreController {

    @Autowired
    OrderForGoodsService orderForGoodsService;

    @Autowired
    StoreService storeService;

    @Autowired
    UserService userService;

    @Autowired
    StoreAmountService storeAmountService;

    //邀请用户注册(生成邀请码 也就是id)

//    @AuthorityName(authorityId = 45, authorityName = "店家 邀请用户注册")
    @StoreAuthority
    @ApiOperation("邀请用户注册")
    @GetMapping("inviteUser")
    public Result inviteUser() {
        log.info("用户:{}  id为: {}", UserUtils.getUserName(), UserUtils.getUserId());
        return Result.ok().data("data", UserUtils.getUserId());
    }


    /**
     * 0    邀请用户注册(生成邀请码)
     * 1    查询订单 (分页条件查询)
     * 2    确定收货(送货员)  (每个订单 单个确认   所有订单一起 确认)
     * 3    确定收货(买家)        (暂时不写 service 是写到user中的 调用 user 中的方法)
     * 4    退货申请( 买家的 )     (暂时不写)
     * 5    查询余额
     * 6    提现
     * 7    查看邀请成功的用户
     * 8    修改地址(很少会用到)
     * 9    修改密码
     */


    /**
     * 1     查看 当天的 我的地址的 订单 分为 已签收 和 未签收      查看当天的订单
     * 前提条件: 订单状态   店家 已签收
     *
     * @param current      当前页码
     * @param limit        每页的条数
     * @param wrapperOrder 查询条件
     * @return 返回总页数 total 和  当前页的 订单信息
     */
//    @AuthorityName(authorityId = 46, authorityName = "店家 条件分页查询订单")
    @StoreAuthority
    @ApiOperation("条件分页查询 订单")
    @PostMapping(value = {"queryOrder/{current}/{limit}", "queryOrder"})
    public Result queryOrder(@PathVariable(value = "current", required = false) Integer current,
                             @PathVariable(value = "limit", required = false) Integer limit,
                             @RequestBody(required = false) WrapperOrder wrapperOrder) {
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        log.debug("wrapperOrder:{}", wrapperOrder);
        if (wrapperOrder == null) {
            wrapperOrder = new WrapperOrder();
        }
        //保证 查询 条件    是我的店里面的
        wrapperOrder.setStoreId(UserUtils.getUserId());
        // 保证查询条件
        Page<OrderForStoreVo> andPage = orderForGoodsService.queryOrder(current, limit, wrapperOrder);
        List<OrderForStoreVo> records = andPage.getRecords();
        List<OrderForStoreVo> orderForStoreVos = OrderStatus.addStatusString(records);

        return Result.ok().data("total", andPage.getTotal()).data("rows", orderForStoreVos);
    }

//     * 2    确定收货(送货员)  (每个订单 单个确认   所有订单一起 确认)

    /**
     * 确定收货的
     *
     * @param orderId id 列表
     * @return 成功或者失败
     */
    // 需要添加事务 一条没成功 就所有没有成功
    // 已经添加 事务了
//    @AuthorityName(authorityId = 47, authorityName = "店家 商家确定收货")
    @StoreAuthority
    @PostMapping("storeIsConfirmationOfReceipt")
    @ApiOperation("商家确定收货")
    public Result storeIsConfirmationOfReceipt(@RequestBody List<Integer> orderId) {
        //判断订单的 状态 是否是 店家未签收 只有店家未签收 时 才可以签收  其他的状态 都是 操作失败
        boolean b = storeService.storeIsConfirmationOfReceipt(orderId);
        if (b) {
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 查询 信息
     */
//    @AuthorityName(authorityId = 48, authorityName = "店家 商家查询自己的信息")
    @StoreAuthority
    @GetMapping("Store")
    @ApiOperation("商家查询自己的信息")
    public Result queryStore() {
        Store store = storeService.getById(UserUtils.getUserId());
        StoreVo storeVo = StoreVo.add(store);
        return Result.ok().data("storeVo", storeVo);
    }


//    @AuthorityName(authorityId = 49, authorityName = "店家 商家修改自己的信息: iphone")
    @StoreAuthority
    @ApiOperation("商家修改自己的信息: iphone")
    @PutMapping("/updateIphone/{iphone}")
    public Result updateIphone(@PathVariable("iphone") String iphone) {
        //判断 iphone 的 合法性  使用正则
        Store store = storeService.getById(UserUtils.getUserId());
        if (Objects.equals(store.getIphone(), iphone)) {
            return Result.ok().message("iphone修改成功");
        }

        //查询 name 是否重复
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("iphone", iphone);
        Store one = storeService.getOne(queryWrapper);
        if (one != null) {
            return Result.error().message("修改失败 iphone 重复");
        }

        //成功修改
        store.setIphone(iphone);
        return storeService.updateById(store)
                ? Result.ok().message("修改成功")
                : Result.error().message("修改失败");
    }


//    @AuthorityName(authorityId = 50, authorityName = "店家 商家修改自己的信息: 地址")
    @StoreAuthority
    @ApiOperation("商家修改自己的信息: 地址")
    @PutMapping("/updateAddress/{address}")
    public Result updateAddress(@PathVariable("address") String address) {
        //判断 iphone 的 合法性  使用正则
        Store store = storeService.getById(UserUtils.getUserId());
        if (Objects.equals(store.getStoreAddress(), address)) {
            return Result.ok().message("address修改成功");
        }
        //判断地址的合法性
        //成功修改
        store.setStoreAddress(address);
        return storeService.updateById(store)
                ? Result.ok().message("修改成功")
                : Result.error().message("修改失败");
    }

//    @AuthorityName(authorityId = 51, authorityName = "店家 商家修改自己的信息: 修改name")
    @StoreAuthority
    @PutMapping("/updateName/{name}")
    @ApiOperation("商家修改自己的信息: 修改name")
    public Result updateName(@PathVariable("name") String name) {
        //判断 name的 合法性  使用正则
        Store store = storeService.getById(UserUtils.getUserId());
        if (Objects.equals(store.getSname(), name)) {
            return Result.ok().message("name修改成功");
        }
        //查询 name 是否重复
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sname", name);
        Store one = storeService.getOne(queryWrapper);
        if (one != null) {
            return Result.error().message("修改失败 name 重复");
        }

        //成功修改
        store.setSname(name);
        return storeService.updateById(store)
                ? Result.ok().message("修改成功")
                : Result.error().message("修改失败");
    }


//    @AuthorityName(authorityId = 52, authorityName = "店家 商家提现")
    @StoreAuthority
    @ApiOperation("商家提现")
    @PutMapping("toCash/{money}")
    public Result toCash(@PathVariable("money") Double money) {
        // 判断 和 合法不合法
        Store store = storeService.getById(UserUtils.getUserId());
        if (money <= 0 || money > store.getBalanceMoney()) {
            return Result.error().message("提现金额 问题");
        }

        boolean b = storeService.toCash(store, money);

        if (b) {
            return Result.ok().message("提现成功: " + money);
        }

        return Result.error().message("提现失败");
    }



    //    7    查看邀请成功的用户
//    @AuthorityName(authorityId = 53, authorityName = "店家 商家查看邀请成功的用户")
    @StoreAuthority
    @ApiOperation("商家查看邀请成功的用户")
    @PostMapping(value = {"getInvited/{current}/{limit}", "getInvited"})
    public Result getInvited(@PathVariable(value = "current", required = false) Integer current,
                             @PathVariable(value = "limit", required = false) Integer limit,
                             @RequestBody(required = false) UserWrapper userWrapper) {
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        if (userWrapper == null) {
            userWrapper = new UserWrapper();
        }
        userWrapper.setStoreId(UserUtils.getUserId());
        Page<User> userToStore = userService.getUserAll(current, limit, userWrapper);

        List<UserToStoreVo> list = new ArrayList<>();
        //给前端 的数据处理

        for (User record : userToStore.getRecords()) {
            UserToStoreVo user = new UserToStoreVo();
            user.setUserName(record.getUserName());
            user.setIphone(record.getIphone());
            user.setCreateTime(record.getCreateTime());
            list.add(user);
        }
        return Result.ok().data("total", userToStore.getTotal()).data("rows", list);
    }

    /*
    查看商家列表 分页条件查询 管理员调用
     */
    @AuthorityName(authorityId = 54, authorityName = "管理员 查看商家列表")
    @PostMapping(value = {"getStoreList/{current}/{limit}", "getStoreList"})
    @ApiOperation("查看商家列表 管理员调用 分页条件查询")
    public Result getStoreList(@PathVariable(value = "current", required = false) Integer current,
                               @PathVariable(value = "limit", required = false) Integer limit,
                               @RequestBody(required = false) StoreWrapper storeWrapper) {
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        if (storeWrapper == null) {
            storeWrapper = new StoreWrapper();
        }
        Page<StoreVo> storeList = storeService.getStoreList(current, limit, storeWrapper);
        return Result.ok()
                .message("查询成功")
                .data("total", storeList.getTotal())
                .data("rows", storeList.getRecords());
    }
    /**
     * 删除店家 逻辑删除
     */
    @AuthorityName(authorityId = 55, authorityName = "管理员 逻辑删除店家")
    @ApiOperation("逻辑删除 店家")
    @DeleteMapping("deleteStore/{storeId}")
    public Result deleteStore(@PathVariable("storeId") Integer storeId) {
        if (storeService.getById(storeId) == null) {
            throw new RuntimeException("商家id 错误");
        }
        storeService.removeById(storeId);
        return Result.ok().message("删除成功");
    }

    /**
     * 新增 小店 注册
     */
    @AuthorityName(authorityId = 56, authorityName = "管理员 商家注册")
    @ApiOperation("商家注册")
    @PostMapping("addStore")
    public Result addStore(@RequestParam("name") String name,
                           @RequestParam("pwd") String pwd
    ) {
        //可以使用正则优化 注册
        if (!RuleUtils.userName(name)) {
            return Result.error().message(RuleUtils.nameError);
        }

        if (!RuleUtils.pwdPattern(pwd)) {
            return Result.error().message(RuleUtils.pwdError);
        }
        // 判断用户名 是否存在
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sname",name);
        Store one = storeService.getOne(queryWrapper);
        //可以注册
        if (one != null){
            return Result.error().message("name 重复");
        }

        Store manage = new Store();
        manage.setSname(name);
        manage.setPwd(pwd);
        return storeService.save(manage)
                ? Result.ok().message("注册成功")
                : Result.error().message("注册失败");
    }

    //分页条件查询
//    @AuthorityName(authorityId = 57, authorityName = "店家 查询自己 分页查询账户流水信息")
    @StoreAuthority
    @ApiOperation("店家 查询自己 分页查询账户流水信息")
    @PostMapping(value = {"/getAmount/{current}/{limit}", "/getAmount"})
    public Result getAmount(@PathVariable(value = "current", required = false) Integer current,
                            @PathVariable(value = "limit", required = false) Integer limit) {
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        StoreAmountWrapper storeAmountWrapper = new StoreAmountWrapper();
        storeAmountWrapper.setStoreId(UserUtils.getUserId());
        Page<UserAmountVo> page = storeAmountService.getAmount(current, limit, storeAmountWrapper);
        // 状态的转化
        List<UserAmountVo> records = page.getRecords();
        List<UserAmountVo> userAmountVos = StoreAmountStatus.intToString(records);

        return Result.ok()
                .message("查询成功")
                .data("total", page.getTotal())
                .data("rows", userAmountVos);
    }

    //分页条件查询
    @AuthorityName(authorityId = 58, authorityName = "管理员 分页查询店家账户流水信息")
    @ApiOperation("admin 分页查询店家账户流水信息")
    @PostMapping(value = {"admin/getAmount/{current}/{limit}", "admin/getAmount"})
    public Result adminGet(@PathVariable(value = "current", required = false) Integer current,
                            @PathVariable(value = "limit", required = false) Integer limit,
                            @RequestBody(required = false) StoreAmountWrapper storeAmountWrapper) {
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        if (storeAmountWrapper == null) {
            storeAmountWrapper = new StoreAmountWrapper();
        }
        Page<UserAmountVo> page = storeAmountService.getAmount(current, limit, storeAmountWrapper);
        // 状态的转化
        List<UserAmountVo> records = page.getRecords();
        List<UserAmountVo> userAmountVos = StoreAmountStatus.intToString(records);

        return Result.ok()
                .message("查询成功")
                .data("total", page.getTotal())
                .data("rows", userAmountVos);
    }
}

